from flask import request
from datetime import datetime
from ..database import mongo_collection
from ..config import Config
from .ip_utils import get_client_ip
import traceback

def log_admin_operation(admin_id, operation, details=None, status="success", resource_id=None, resource_type=None):
    """
    记录管理员操作到MongoDB
    
    参数:
    - admin_id: 管理员ID
    - operation: 操作类型(例如: 'create', 'update', 'delete', 'query')
    - details: 操作详情，可以是任何可JSON序列化的对象
    - status: 操作状态，'success'或'failed'
    - resource_id: 操作的资源ID
    - resource_type: 操作的资源类型(例如: 'user', 'device', 'announcement')
    
    返回:
    - None
    """
    # 判断是否为查询类操作，如果是查询操作则不记录日志
    if operation.startswith('query_') or 'get_' in operation or request.method == 'GET':
        # 只打印日志但不记录到数据库
        print(f"[INFO] 跳过查询操作日志记录: {operation}, admin_id: {admin_id}")
        return
    
    try:
        # 获取管理员名称
        admin_name = "未知管理员"
        try:
            from ..models import Admin
            admin = Admin.query.get(admin_id)
            if admin:
                admin_name = admin.admin_name
        except Exception as name_error:
            print(f"[WARNING] 获取管理员名称失败: {str(name_error)}")
        
        # 获取真实客户端IP
        client_ip = get_client_ip()
        
        log_data = {
            "admin_id": admin_id,
            "admin_name": admin_name,
            "operation": operation,
            "timestamp": datetime.now(),
            "ip": client_ip,
            "user_agent": request.user_agent.string if request.user_agent else None,
            "path": request.path,
            "method": request.method,
            "status": status,
        }
        
        # 添加可选字段
        if details:
            log_data["details"] = details
        if resource_id:
            log_data["resource_id"] = resource_id
        if resource_type:
            log_data["resource_type"] = resource_type
        
        # 记录到MongoDB
        with mongo_collection(Config.MONGODB_COLLECTIONS["admin_logs"]) as collection:
            collection.insert_one(log_data)
            
    except Exception as e:
        print(f"[ERROR] 记录管理员操作日志失败: {str(e)}")
        traceback.print_exc()
        # 这里我们不抛出异常，因为日志记录不应该影响主要业务流程

def get_admin_id_from_request():
    """
    从请求中获取admin_id，只从header中获取
    
    返回:
    - admin_id: 管理员ID或None
    """
    # 从header中获取
    admin_id = request.headers.get('admin_id')
    return admin_id 